package day190611;

/**
 * @author LI DUO
 * @version 1.0
 * @date 2019/6/11 下午 05:02
 * 5. 最长回文子串
 */
public class LongestPalindrome {

    public String longestPalindrome2(String s) {
        if (s == null) {
            return null;
        }
        String result = "";
        int length = s.length();
        int i = 0, j = 1;
        while (i < length && j <= length) {
            String str = s.substring(i, j);
            if (isPal(str)) {
                if (str.length() >= result.length()) {
                    result = str;
                }
            }
            j ++;
            if (j > length) {
                i ++;
                j = i + 1;
            }
        }
        return result;
    }

    public boolean isPal(String s) {
        StringBuilder builder = new StringBuilder(s);
        return builder.reverse().toString().equalsIgnoreCase(s);
    }

    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(i, i , s);
            int len2 = expandAroundCenter(i, i + 1, s);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    public int expandAroundCenter(int left, int right, String s) {
        int l = left, r = right;
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l --;
            r ++;
        }
        return r - l - 1;
    }

    public static void main(String[] args) {
        LongestPalindrome palindrome = new LongestPalindrome();
        String s = "anugnxshgonmqydttcvmtsoaprxnhpmpovdolbidqiyqubirkvhwppcdyeouvgedccipsvnobrccbndzjdbgxkzdbcjsjjovnhpnbkurxqfupiprpbiwqdnwaqvjbqoaqzkqgdxkfczdkznqxvupdmnyiidqpnbvgjraszbvvztpapxmomnghfaywkzlrupvjpcvascgvstqmvuveiiixjmdofdwyvhgkydrnfuojhzulhobyhtsxmcovwmamjwljioevhafdlpjpmqstguqhrhvsdvinphejfbdvrvabthpyyphyqharjvzriosrdnwmaxtgriivdqlmugtagvsoylqfwhjpmjxcysfujdvcqovxabjdbvyvembfpahvyoybdhweikcgnzrdqlzusgoobysfmlzifwjzlazuepimhbgkrfimmemhayxeqxynewcnynmgyjcwrpqnayvxoebgyjusppfpsfeonfwnbsdonucaipoafavmlrrlplnnbsaghbawooabsjndqnvruuwvllpvvhuepmqtprgktnwxmflmmbifbbsfthbeafseqrgwnwjxkkcqgbucwusjdipxuekanzwimuizqynaxrvicyzjhulqjshtsqswehnozehmbsdmacciflcgsrlyhjukpvosptmsjfteoimtewkrivdllqiotvtrubgkfcacvgqzxjmhmmqlikrtfrurltgtcreafcgisjpvasiwmhcofqkcteudgjoqqmtucnwcocsoiqtfuoazxdayricnmwcg";
        System.out.println(palindrome.longestPalindrome(s));
    }
}
